#-*-coding:utf-8-*-
# Create your views here.
import time,datetime

from django.core.paginator import Paginator, InvalidPage
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import loader, RequestContext
import os,sys
import md5,random
import Image
from crm.models import *
from crm.common import login_required
from pagination import PaginationWrap

from crmv2.models import *


"""项目课程学生名单"""
def student_list(request,pc_id='0'):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    p_list = Projects.objects.order_by('id')

    try:
        pcinfo_obj=get_object_or_404(Project_course_info, pk = int(pc_id))
    except:
        pcinfo_obj=''
    ttlist=[]
    isin_list=[]
    pc_list=Project_course_info.objects.filter(project=pcinfo_obj.project,is_removed=0)
    for pc in pc_list:
        if pc.period not in isin_list:
            ttlist.append(pc)
            isin_list.append(pc.period)

    pc_list=Program_student_course.objects.filter(pcid=pc_id,is_removed=0).order_by("-id")
    psc_list=[]
    today=datetime.date.today()
    for pc in pc_list:
        d_dict={}
        try:
            sdate=datetime.date(*[int(i) for i in pc.class_start.split('-')])
            if sdate<today:
                d_dict['status']='預选'
            else:
                d_dict['status']=''
        except:
            d_dict['status']=''
        d_dict['obj']=pc
        psc_list.append(d_dict)
    return render_to_response('course/student_list.html', {'pc_list':psc_list,'pcinfo_obj':pcinfo_obj,'p_list':p_list,'ttlist':ttlist})



def student_list_test(request):
    pc_list=Program_student_course.objects.filter().order_by("-id")
    i=0
    j=0
    for pc in pc_list:
        j+=1
        try:
            pcinfo_obj=Project_course_info.objects.get(project = pc.project,period=pc.period,is_removed=0)
            pc.pcid=pcinfo_obj.id
            pc.save()
            i+=1
        except:
            pass
    strd="all:"+str(j)+";deal:"+str(i)
    return HttpResponse(strd)

def classes(request):
    pid=request.REQUEST.get('pid',"")
    courseid=request.REQUEST.get('courseid',"0")
    if pid=="":
        try:
            pid=request.session['program']
        except:
            pid=0
    try:
        pid=int(pid)
    except:
        pass

    #get classes list
    p_obj = Projects.objects.get(pk = pid)
    c_list=Project_course_info.objects.filter(project=p_obj,is_removed=0).order_by("-period")
    s_list=''
    textbook = ''
    countstudent=0
    if courseid:
        try:
            courseid=int(courseid)
            c_obj = Project_course_info.objects.get(pk = courseid)
            s_list=Program_student_course.objects.filter(project=p_obj,is_removed=0,period=c_obj.period,status='Upcoming').order_by("-id")
            countstudent=s_list.count()
        except:
            pass

    theyearmon=time.strftime('%Y-%m',time.localtime(time.time()))
    theym=theyearmon
    #项目
    if courseid:
        mp_obj=c_obj
    else:
        mp_obj=''
        mp_list=Project_course_info.objects.filter(project=p_obj,is_removed=0,period__icontains=theyearmon).order_by("-period")[:1]
        for mp in mp_list:
            mp_obj=mp
        theym=theyearmon
        if mp_obj=='':
            nmon=time.strftime('%m',time.localtime(time.time()))
            nyear=time.strftime('%Y',time.localtime(time.time()))
            try:
                nmon=int(nmon)
            except:
                pass
            try:
                yy=int(nyear)
            except:
                pass
            if nmon==12:
                yy=yy+1
                theym=str(yy)+"-01"
            else:
                nmon=nmon+1
                if nmon<10:
                    nmon='0'+str(nmon)
                theym=str(nyear)+"-"+str(nmon)
            mp_list2=Project_course_info.objects.filter(project=p_obj,is_removed=0,period__icontains=theym).order_by("period")[:1]
            for mp in mp_list2:
                mp_obj=mp
    if mp_obj!='':
        mp_obj.textbook = mp_obj.textbook
    p_list = Projects.objects.order_by('-position')
    return render_to_response('course/classes.html',
    {'p_list':p_list,'p_obj':p_obj,'c_list':c_list,'s_list':s_list,'courseid':int(courseid),
    'countstudent':countstudent,'mp_obj':mp_obj,'theym':theym
    })


def changeclassstatus(request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.META.get('HTTP_X_REQUESTED_WITH','').lower() == 'xmlhttprequest':
        id=request.REQUEST.get('id',"")
        status=request.REQUEST.get('value','')
        if id:
            try:
                psc_obj=Program_student_course.objects.get(pk=int(id))
                psc_obj.status=status
                psc_obj.save()
                return HttpResponse('ok')
            except:
                return HttpResponse('error')
        else:
            return HttpResponse('error2')
    else:
        return HttpResponse('there is something wrong')


def setallclassstatus(request):
    pid=request.REQUEST.get('pid',"")
    courseid=request.REQUEST.get('courseid',"0")
    gourl="/v2/classes/?pid="+str(pid)+"&courseid="+str(courseid)
    try:
        pid=int(pid)
        p_obj = Projects.objects.get(pk = pid)
        courseid=int(courseid)
        c_obj = Project_course_info.objects.get(pk = courseid)
        s_list=Program_student_course.objects.filter(project=p_obj,is_removed=0,period=c_obj.period).order_by("-id")
        for s in s_list:
            s.status='Completed'
            s.save()
    except:
        pass
    return HttpResponseRedirect(gourl)


